<?php
/**
 * 管理员验证器
 */

namespace app\msgapi\validate;

use app\msgapi\model\System;
use think\Validate;

class AdminUser extends Validate
{
    protected $rule = [
        'username|用户名'   => 'require|length:2,20|unique:admin_user',// username字段的值是否在admin_user表（不包含前缀）中唯一
        'old_password|原密码' => 'require|different:password',
        'password|新密码' => 'require|checkPass',
        'confirm_password|重复密码' => 'require|confirm:password',
        'email|敏感词消息接收邮件' => 'email',
    ];

    protected $message = [
        'confirm_password.confirm'  =>  '两次新密码输入不一致',
        'old_password.different' => '新旧密码不能相同',
        'email.email' => '敏感词消息接收邮件格式错误'
    ];

    public function sceneAdd()
    {
        return $this->only(['username','password','confirm_password']);    // 仅验证密码字段
    }
    // 管理员修改
    public function sceneEdit()
    {
        return $this->only(['username','password','confirm_password','email'])    // 仅验证密码字段
            ->append('password','requireWith:confirm_password')     // 重复密码有值时，密码必须
            ->append('confirm_password','requireWith:password')     // 密码有值时，confirm_password必须
            ->remove('password', 'require')
            ->remove('confirm_password','require');// 移除规则
    }
    // 自己更新
    public function sceneUp()
    {
        return $this->only(['old_password','password','confirm_password','email']);    // 仅验证密码字段
    }

    // 自己更新
    public function sceneUpemail()
    {
        return $this->only(['email']);    // 仅验证邮箱字段
    }

    // 自定义验证规则
    protected function checkPass($value,$rule,$data)
    {
        if($value){ // 密码有值判定
            $pass_config = System::getSys('pass_config');
            if(strlen($value) < $pass_config['minlength']){
                return '密码最小长度'.$pass_config['minlength'];
            }
            if(strlen($value) > $pass_config['maxlength']){
                return '密码最大长度'.$pass_config['maxlength'];
            }
            $msg = ['1'=>'数字、',2=>'大写字母、',3=>'小写字母、',4=>'特殊字符：~!@&%#_'];
            $return_msg = '密码必须包含';
            $_rules = ['1'=>'(?=.*[0-9])',2=>'(?=.*[A-Z])',3=>'(?=.*[a-z])',4=>'(?=.*[~!@&%#_])'];
            $_rule = '/^';
            foreach ($pass_config['strength'] as $v){
                $return_msg .= $msg[$v];
                $_rule .= $_rules[$v];
            }
            $_rule .= '[a-zA-Z0-9~!@&%#_]{'.$pass_config['minlength'].','.$pass_config['maxlength'].'}$/';
            if(!preg_match($_rule,$value)){
                return $return_msg;
            }
        }
        return true;
    }
}